/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.gdevelop.gwtxp.rebind.gwt;

import com.gdevelop.gwtxp.rebind.AbstractTag;
import com.gdevelop.gwtxp.rebind.GwtXPCreator;
import com.gdevelop.gwtxp.rebind.Tag;

import com.gdevelop.gwtxp.rebind.el.ELParser;
import com.gdevelop.gwtxp.rebind.el.Node;

import com.google.gwt.core.ext.typeinfo.NotFoundException;

public class ErrorsTag extends AbstractTag{
  private static final String DEFAULT_ERROR_STYLE_NAME = "error";
  private static final String DEFAULT_SUCCESS_STYLE_NAME = "success";

  public ErrorsTag() {
  }

  public Class getUIClass() {
    return null;
  }

  public void generateDeclaration() throws NotFoundException {
    String errorStyleName = this.getAttribute("errorStyleName");
    if (errorStyleName == null){
      errorStyleName = DEFAULT_ERROR_STYLE_NAME;
    }
    String successStyleName = this.getAttribute("successStyleName");
    if (successStyleName == null){
      successStyleName = DEFAULT_SUCCESS_STYLE_NAME;
    }

    out.println("ErrorsWidget " + varName + " = new ErrorsWidget(\"" + errorStyleName + "\", \"" + successStyleName + "\");");
  }

  public void generateAddUI(Tag child) {
    // No-op
  }
  
  public void generateInitStart() throws NotFoundException{
    String errorMessage = this.getAttribute("errorMessage");
    if (errorMessage == null){
      errorMessage = "Errors";
    }
    
    String errorStyleName = this.getAttribute("errorStyleName");
    if (errorStyleName == null){
      errorStyleName = DEFAULT_ERROR_STYLE_NAME;
    }
    
    out.println();
    out.println("// " + varName);
    if (parent == null){
      out.println("initWidget(" + varName + ");");
    }

    out.println(GwtXPCreator.VAR_NAME_DATABINDING_CONTEXT + ".bindValue(");
    out.indent();
    out.println("new HasTextObservableValue(" + varName + ")");
    out.print(", ");
    Node elNode = ELParser.parse(errorMessage);
    out.println("new ValidationStatusObservableValue(" 
                + GwtXPCreator.VAR_NAME_DATABINDING_CONTEXT + ".getBindings(), " 
                + elNode.generateGetExpression(elContext) + ", \"" + errorStyleName + "\")");
    out.println(", null, null);");
  }
}
